package com.ydl.shopping.core.entity;

import com.ydl.shopping.domain.TbLoginInfo;
import com.ydl.shopping.domain.TbUser;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Data
@AllArgsConstructor
public class LoginUser implements UserDetails {
    /**
     * 用户ID
     */
    private Long userId;

    /**
     * 用户名称
     */
    private String username;

    /**
     * 手机号
     */
    private String tel;

    /**
     * 用户唯一标识
     */
    private String token;

    /**
     * 用户信息
     */
    private TbUser tbUser;

    /**
     * 登录信息
     */
    private TbLoginInfo tbLoginInfo;

    /**
     * 权限标识
     */
    private List<String> perms;

    /**
     * 权限列表
     */
    private List<SimpleGrantedAuthority> authorities;

    public LoginUser(TbUser tbUser, TbLoginInfo tbLoginInfo, List<String> perms) {
        this.userId = tbUser.getId();
        this.username = tbUser.getUsername();
        this.tel = tbUser.getTel();
        this.tbUser = tbUser;
        this.tbLoginInfo = tbLoginInfo;
        this.perms = perms;
    }

    /** 用户的权限集， 默认需要添加前缀 */
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (authorities != null) {
            return authorities;
        }
        authorities = perms.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        return authorities;
    }

    /** 用户的加密后的密码， 不加密会使用前缀 */
    @Override
    public String getPassword() {
        return tbUser.getPassword();
    }

    /** 应用内唯一的用户名 */
    @Override
    public String getUsername() {
        return tbUser.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return false;
    }

    @Override
    public boolean isAccountNonLocked() {
        return false;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return false;
    }

    @Override
    public boolean isEnabled() {
        return tbUser.getStatus() < 0;
    }
}
